# 文件名：web_control_config.py
from flask import Flask, render_template_string, request, redirect, url_for, flash
from obsws_python import ReqClient

app = Flask(__name__)
app.secret_key = 'supersecret'

# 默认 OBS 配置
OBS_CONFIG = {
    "host": "192.168.0.111",
    "port": 4455,
    "password": "W13YYEkQaHFL6kLT",
    "media_source_name": "11"
}

# 默认片段
segments = {
    1: 0,
    2: 60_000,
    3: 120_000
}

# OBS 客户端
client = None

# HTML 模板
HTML_TEMPLATE = """
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>无人直播控制器</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { padding: 2rem; background-color: #f8f9fa; }
    h2 { margin-bottom: 1.5rem; }
    .card { margin-bottom: 1.5rem; }
    .card-header { font-weight: bold; }
    .form-label { font-weight: 500; }
    .btn { min-width: 100px; }
  </style>
</head>
<body>
  <div class="container">
    <h2 class="text-primary">AI无人直播切片控制器</h2>

    <!-- OBS 配置卡片 -->
    <div class="card shadow-sm">
      <div class="card-header bg-primary text-white">OBS 配置</div>
      <div class="card-body">
        <form method="post" action="/set_config">
          <div class="mb-2">
            <label class="form-label">OBS 主机地址 (Host)</label>
            <input type="text" name="host" value="{{ config['host'] }}" class="form-control" placeholder="例如 192.168.0.111">
          </div>
          <div class="mb-2">
            <label class="form-label">OBS 端口 (Port)</label>
            <input type="number" name="port" value="{{ config['port'] }}" class="form-control" placeholder="默认 4455">
          </div>
          <div class="mb-2">
            <label class="form-label">OBS 密码 (Password)</label>
            <input type="text" name="password" value="{{ config['password'] }}" class="form-control" placeholder="OBS WebSocket 密码">
          </div>
          <div class="mb-2">
            <label class="form-label">媒体源名称 (Media Source)</label>
            <input type="text" name="media_source_name" value="{{ config['media_source_name'] }}" class="form-control" placeholder="如 '11'">
          </div>
          <button class="btn btn-success mt-2">保存配置</button>
        </form>
      </div>
    </div>

    <!-- 片段控制卡片 -->
    <div class="card shadow-sm">
      <div class="card-header bg-success text-white">片段控制</div>
      <div class="card-body">
        <form method="post" action="/play" class="d-flex align-items-center gap-2">
          <label class="form-label mb-0">选择片段：</label>
          <select name="segment" class="form-select w-auto">
            {% for num in segments %}
              <option value="{{num}}">{{num}}</option>
            {% endfor %}
          </select>
          <button class="btn btn-primary">播放</button>
        </form>
      </div>
    </div>

    <!-- 片段时间配置卡片 -->
    <div class="card shadow-sm">
      <div class="card-header bg-info text-white">片段时间配置（毫秒）</div>
      <div class="card-body">
        <form method="post" action="/set_segments">
          <div class="row g-2">
            {% for num, start in segments.items() %}
              <div class="col-md-4">
                <label class="form-label">片段 {{num}} 起始时间</label>
                <input type="number" name="seg_{{num}}" value="{{start}}" class="form-control" placeholder="毫秒数">
              </div>
            {% endfor %}
          </div>
          <button class="btn btn-info mt-2">保存片段时间</button>
        </form>
      </div>
    </div>

    <!-- 消息提示 -->
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <div class="mt-3">
          {% for message in messages %}
            <div class="alert alert-warning alert-dismissible fade show" role="alert">
              {{ message }}
              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
          {% endfor %}
        </div>
      {% endif %}
    {% endwith %}
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
<!-- 页面底部版权 -->
<footer class="mt-5 py-3 bg-light text-center text-muted border-top">
  <div>
    © 2025 激发科技有限公司 - AI无人直播切片控制器 | 保留所有权利
  </div>
</footer>

</html>
"""



def get_client():
    global client
    if client is None:
        client = ReqClient(
            host=OBS_CONFIG["host"],
            port=OBS_CONFIG["port"],
            password=OBS_CONFIG["password"]
        )
    return client


@app.route("/", methods=["GET"])
def index():
    return render_template_string(HTML_TEMPLATE, config=OBS_CONFIG, segments=segments)


@app.route("/set_config", methods=["POST"])
def set_config():
    OBS_CONFIG["host"] = request.form["host"]
    OBS_CONFIG["port"] = int(request.form["port"])
    OBS_CONFIG["password"] = request.form["password"]
    OBS_CONFIG["media_source_name"] = request.form["media_source_name"]
    # 重置客户端
    global client
    client = None
    flash("✅ OBS 配置已保存")
    return redirect(url_for('index'))


@app.route("/set_segments", methods=["POST"])
def set_segments():
    for key in request.form:
        if key.startswith("seg_"):
            seg_num = int(key.split("_")[1])
            segments[seg_num] = int(request.form[key])
    flash("✅ 片段时间已保存")
    return redirect(url_for('index'))


@app.route("/play", methods=["POST"])
def play():
    seg_num = int(request.form["segment"])
    if seg_num not in segments:
        flash(f"❌ 片段 {seg_num} 不存在！")
        return redirect(url_for('index'))
    start_time = segments[seg_num]

    client = get_client()
    client.set_media_input_cursor(OBS_CONFIG["media_source_name"], start_time)
    flash(f"✅ 已切换到片段 {seg_num}，起始 {start_time / 1000:.1f} 秒")
    return redirect(url_for('index'))


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)
